<template>
  <section>
    <van-sticky>
      <PageHeader :title="title"/>
    </van-sticky>

    <div class="msg-wrapper flex flex-col pd10">
      <div class="flex flex-row mb10 chat-member" v-if="chatMember">
        <div class="flex flex-row pr10">
          <img :src="chatUser.avatar_url ? chatUser.avatar_url : STATIC_BASE_URL + '/images/mp/gender.png'"
               class="avatar" @click="$router.push({ name: 'MemberProfile', query: { id: chatMember.id }})"/>
        </div>

        <div class="flex flex-col flex-1" @click="$router.push({ name: 'MemberProfile', query: { id: chatMember.id }})">
          <div class="flex flex-row flex-left font-big strong">{{chatUser.nick}}</div>
          <div class="flex flex-col bg-color-white pd10 round-box mt10 info">
            <img :src="chatMember.photo_url ? chatMember.photo_url : STATIC_BASE_URL + '/images/mp/gender.png'"
                 class="flex photo"/>
            <div class="flex flex-row flex-left mt10 font-common">
              <span class="font-big strong">{{chatUser.nick}}</span><span v-if="chatMember.birthday>0"> · {{chatMember.age}}岁</span><span
              v-if="chatMember.live_city_str"> · {{chatMember.live_city_str}}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="pd10 bg-color-gray font-common color-gray-dark text-center">
        聊天涉及钱财问题，请保持警惕，避免上当受骗。若发现可疑行为，请及时举报。
      </div>

      <div class="flex flex-col" v-for="(item, index) in msgList" :key="index" v-if="chatUser">
        <div class="text-center pd5 font-common color-gray">{{item.send_time|timeFormat('yyyy-MM-dd hh:mm:ss')}}</div>
        <div class="flex flex-row font-common mb10 receive-item" v-if="item.send_uid==chatUser.id">
          <img :src="chatUser && chatUser.avatar_url ? chatUser.avatar_url : STATIC_BASE_URL + '/images/mp/gender.png'"
                class="flex avatar"
                @click="$router.push({ name: 'MemberProfile', query: { id: chatMember.id }})"/>
          <div class="flex flex-1 flex-col pl10">
            <div class="flex flex-row flex-left"
                 v-if="chatUser"
                 @click="$router.push({ name: 'MemberProfile', query: { id: chatMember.id }})">
              {{chatUser.nick}}
            </div>
            <div class="flex flex-row flex-left mt5 relative">
              <div class="bg-color-white inline-block content pd10 text-centerV" v-html="item.msg" v-if="unlock"></div>
              <div class="bg-color-white inline-block content pd10 text-centerV" v-else>
                {{item.msg}}<i class="iconfont icon-jinggao ml5 color-red" style="font-size: 20px;" @click="chargeOverlayVisible=true" />
              </div>
            </div>
          </div>
        </div>

        <div class="flex flex-row font-common mb10 send-item" v-else-if="item.to_uid==chatUser.id">
          <div class="flex flex-1 flex-col pr10">
            <div class="flex flex-row flex-right" v-if="user">
              我
            </div>
            <div class="flex flex-row flex-right mt5 relative">
              <div class="inline-block color-white content pd10" v-html="item.msg"></div>
            </div>
          </div>
          <img :src="user && user.avatar_url ? user.avatar_url : STATIC_BASE_URL + '/images/mp/gender.png'" class="flex avatar"/>
        </div>

      </div>

      <div ref="msg_end" style="height:0px; overflow:hidden"></div>
    </div>

    <div class="send-input-wrapper bg-color-white flex flex-col">
      <div class="bg-color-white pd10 flex flex-row flex-centerV">
        <div class="flex flex-1 flex-row">
          <input type="text" :value="msgContent" class="send-input" id="msgInput" ref="msgInput"/>
        </div>

        <div class="flex flex-row flex-center pl10 color-dark">
          <i class="iconfont icon-biaoqing" style="font-size: 24px;" @click="toggleEmojiWrapper"/>
        </div>

        <div class="flex flex-row flex-center pl10">
          <van-button type="primary" size="small" round @click="send(null)">发送</van-button>
        </div>
      </div>

      <div class="emoji-wrapper" v-if="emojiWrapperVisible">
        <div class="flex flex-row faces">
          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/1.gif'" @click="send('[face_1]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/2.gif'" @click="send('[face_2]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/3.gif'" @click="send('[face_3]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/4.gif'" @click="send('[face_4]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/5.gif'" @click="send('[face_5]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/6.gif'" @click="send('[face_6]')" />
          </div>
        </div>

        <div class="flex flex-row faces">
          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/7.gif'" @click="send('[face_7]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/8.gif'" @click="send('[face_8]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/9.gif'" @click="send('[face_9]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/10.gif'" @click="send('[face_10]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/11.gif'" @click="send('[face_11]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/12.gif'" @click="send('[face_12]')" />
          </div>
        </div>

        <div class="flex flex-row faces">
          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/13.gif'" @click="send('[face_13]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/14.gif'" @click="send('[face_14]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/15.gif'" @click="send('[face_15]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/16.gif'" @click="send('[face_16]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/17.gif'" @click="send('[face_17]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/18.gif'" @click="send('[face_18]')" />
          </div>
        </div>

        <div class="flex flex-row faces">
          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/19.gif'" @click="send('[face_19]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/20.gif'" @click="send('[face_20]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/21.gif'" @click="send('[face_21]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/22.gif'" @click="send('[face_22]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/23.gif'" @click="send('[face_23]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/24.gif'" @click="send('[face_24]')" />
          </div>
        </div>

        <div class="flex flex-row faces">
          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/25.gif'" @click="send('[face_25]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/26.gif'" @click="send('[face_26]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/27.gif'" @click="send('[face_27]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/28.gif'" @click="send('[face_28]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/29.gif'" @click="send('[face_29]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/30.gif'" @click="send('[face_30]')" />
          </div>
        </div>

        <div class="flex flex-row faces">
          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/31.gif'" @click="send('[face_31]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/32.gif'" @click="send('[face_32]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/33.gif'" @click="send('[face_33]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/34.gif'" @click="send('[face_34]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/35.gif'" @click="send('[face_35]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/36.gif'" @click="send('[face_36]')" />
          </div>
        </div>

        <div class="flex flex-row faces">
          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/37.gif'" @click="send('[face_37]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/38.gif'" @click="send('[face_38]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/39.gif'" @click="send('[face_39]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/40.gif'" @click="send('[face_40]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/41.gif'" @click="send('[face_41]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/42.gif'" @click="send('[face_42]')" />
          </div>
        </div>

        <div class="flex flex-row faces">
          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/43.gif'" @click="send('[face_43]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/44.gif'" @click="send('[face_44]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/45.gif'" @click="send('[face_45]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/46.gif'" @click="send('[face_46]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/47.gif'" @click="send('[face_47]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/48.gif'" @click="send('[face_48]')" />
          </div>
        </div>

        <div class="flex flex-row faces">
          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/49.gif'" @click="send('[face_49]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/50.gif'" @click="send('[face_50]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/51.gif'" @click="send('[face_51]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/52.gif'" @click="send('[face_52]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/53.gif'" @click="send('[face_53]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/54.gif'" @click="send('[face_54]')" />
          </div>
        </div>

        <div class="flex flex-row faces">
          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/55.gif'" @click="send('[face_55]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/56.gif'" @click="send('[face_56]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/57.gif'" @click="send('[face_57]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/58.gif'" @click="send('[face_58]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/59.gif'" @click="send('[face_59]')" />
          </div>

          <div class="flex flex-row flex-center flex-1 pd5">
            <img :src="STATIC_BASE_URL + 'images/faces/60.gif'" @click="send('[face_60]')" />
          </div>
        </div>

      </div>
    </div>

    <van-overlay :show="chargeOverlayVisible">
      <div class="flex flex-col flex-center recharge-wrapper" style="height: 100%;">
        <div class="flex flex-col pd20 round-box bg-color-white recharge-box">
          <div class="flex flex-row flex-center strong font-biger">
            解锁聊天<span class="font-common color-gray-dark ml10">(<span
            class="color-red">{{chargePrice}}</span>)金币</span>
          </div>

          <div class="flex flex-row flex-center mt20">
            <div class="flex flex-row flex-center pr10">
              <i class="iconfont icon-viphuiyuanhuangguan" style="font-size: 26px;color: #ff0000;"/>
            </div>

            <div class="flex flex-col flex-centerH flex-1">
              <div class="flex flex-row flex-left strong font-biger">VIP特权</div>
              <div class="flex flex-row flex-left color-gray font-common">免费聊天</div>
            </div>

            <div class="flex flex-row flex-center pl10">
              <van-button type="warning" round size="small" @click="$router.push({name: 'VipBuy'})">马上升级</van-button>
            </div>
          </div>

          <div class="flex flex-row flex-center mt20">
            <div class="flex flex-row flex-center pr10">
              <i class="iconfont icon-taojinbi" style="font-size: 26px;color: #9266f9;"/>
            </div>

            <div class="flex flex-col flex-centerH flex-1">
              <div class="flex flex-row flex-left strong font-biger">金币支付</div>
              <div class="flex flex-row flex-left color-gray font-common">当前可用金币：<span class="color-green">{{user && user.gold_coin ? user.gold_coin : 0}}</span>
              </div>
            </div>

            <div class="flex flex-row flex-center pl10">
              <van-button type="warning"
                          round
                          size="small"
                          @click="onCreateGoldCoinChargeOrder">立即参加
              </van-button>
            </div>
          </div>

          <div class="flex flex-row flex-center mt20">
            <div class="flex flex-row flex-center pr10">
              <i class="iconfont icon-weixinzhifu" style="font-size: 26px;color: #16c2c2;"/>
            </div>

            <div class="flex flex-col flex-centerH flex-1">
              <div class="flex flex-row flex-left strong font-biger">在线支付</div>
              <div class="flex flex-row flex-left color-gray font-common">尽享聊天通道</div>
            </div>

            <div class="flex flex-row flex-center pl10">
              <van-button type="warning" round size="small" @click="onCreateChargeOrder">立即支付</van-button>
            </div>
          </div>

        </div>

        <div class="flex flex-row flex-center pd20">
          <i class="iconfont icon-guanbi" style="font-size: 34px; color: #FFFFFF;"
             @click="chargeOverlayVisible=false"/>
        </div>
      </div>
    </van-overlay>
  </section>
</template>

<script>
  import Vue from 'vue';
  import {Toast, Dialog, Sticky, Button, Overlay, Row, Col} from 'vant';
  import PageHeader from "../componets/PageHeader";
  import {
    chatMessageReadUri,
    chatMessageSendUri, chatMessageSessionUri,
    memberProfileByUserIdUri, serviceChargeOrderCreateUri,
    STATIC_BASE_URL, wechatJsApiConfigUri, wxPayQueryUri, wxPayServiceChargeOrderPayTradeUri
  } from "../../common/api";
  import {IID_TYPE_UNLOCK_CHAT_SESSION} from "../../common/constants";

  Vue.use(Toast).use(Dialog).use(Sticky).use(Button).use(Overlay).use(Row).use(Col);

  let messageList = {};

  export default {
    components: {
      PageHeader
    },
    data() {
      return {
        STATIC_BASE_URL: STATIC_BASE_URL,
        siteConfig: null,
        title: '发消息',
        msgContent: '',
        userId: 0,
        member: null,
        user: null,
        chatMember: null,
        chatUser: null,
        emojiWrapperVisible: false,
        msgList: [],
        unlock: false,
        chargeOverlayVisible: false,
        chargePrice: 0.00
      }
    },
    methods: {
      getJsApiConfig() {
        if(!isWxServiceEnable) {
          return;
        }
        const that = this;
        const url = wechatJsApiConfigUri + '?url=' + encodeURIComponent(window.location.href);
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.toast(msg);
          } else {
            wx.config({
              debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
              appId: data.appId, // 必填，公众号的唯一标识
              timestamp: data.timestamp, // 必填，生成签名的时间戳
              nonceStr: data.nonceStr, // 必填，生成签名的随机串
              signature: data.signature,// 必填，签名
              jsApiList: ['hideOptionMenu', 'hideMenuItems', 'hideAllNonBaseMenuItem', 'chooseWXPay'] // 必填，需要使用的JS接口列表
            });

            wx.ready(function () {
              console.log('wx配置成功');
              wx.hideAllNonBaseMenuItem();
            });

            wx.error(function (res) {
              console.log('wx配置出错');
            });
          }
        }, response => {
          // error callback
        })
      },
      onCreateGoldCoinChargeOrder() {
        if(parseFloat(this.user.gold_coin) < parseFloat(this.chargePrice)) {
          Toast('金币不足');
          return;
        }
        const that = this;
        const fromuid = localStorage.getItem('fromuid') ? localStorage.getItem('fromuid') : 0;

        const url = serviceChargeOrderCreateUri + '?fromuid=' + fromuid + '&iid=' + this.chatUser.id + '&iid_type=' + IID_TYPE_UNLOCK_CHAT_SESSION + '&money_type=gold_coin';
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.toast(msg);
          } else {
            that.chargeOverlayVisible = false;
            that.getSession();
          }
        }, response => {
          // error callback
        })
      },
      onCreateChargeOrder() {
        const that = this;
        const fromuid = localStorage.getItem('fromuid') ? localStorage.getItem('fromuid') : 0;

        const url = serviceChargeOrderCreateUri + '?fromuid=' + fromuid + '&iid=' + this.chatUser.id + '&iid_type=' + IID_TYPE_UNLOCK_CHAT_SESSION;
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.toast(msg);
          } else {
            that.chargeOverlayVisible = false;
            that.chooseWXPay(data.order_sn);
          }
        }, response => {
          // error callback
        })
      },
      chooseWXPay(orderSn) {
        const that = this;
        const url = wxPayServiceChargeOrderPayTradeUri + '?order_sn=' + orderSn;
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.toast(msg);
          } else {
            const payParams = JSON.parse(data.pay_params);
            wx.chooseWXPay({
              timestamp: payParams.timeStamp,
              nonceStr: payParams.nonceStr,
              package: payParams.package,
              signType: payParams.signType,
              paySign: payParams.paySign,
              success: function (res) {
                // 支付成功后的回调函数
                that.onPaied(orderSn, data.pay_trade_no);
              },
              fail: function (res) {
                that.toast('支付失败');
              }
            });
          }
        }, response => {
          // error callback
        });
      },
      onPaied(orderSn, payTradeNo) {
        const that = this;
        const url = wxPayQueryUri + '?pay_trade_no=' + payTradeNo;
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.toast(msg);
          } else {
            if (data.success == 1) {
              that.getSession();
            } else {
              that.toast('支付出错，请重试或联系客服付款');
            }
          }
        }, response => {
          // error callback
        })
      },
      toggleEmojiWrapper() {
        this.emojiWrapperVisible = !this.emojiWrapperVisible;
        if (this.emojiWrapperVisible) {
          this.$refs.msgInput.focus();
        }
      },
      getMemberProfile() {
        if(this.chatMember) {
          return;
        }
        const that = this;
        const url = memberProfileByUserIdUri + '?user_id=' + this.userId;
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.toast(msg);
          } else {
            that.chatMember = data.member;
            that.chatUser = data.user;
            that.title = data.user.nick;
            that.getSession();
          }
        }, response => {
          // error callback
        })
      },
      getSession() {
        const that = this;
        const url = chatMessageSessionUri + '?send_uid=' + this.chatUser.id;
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.toast(msg);
          } else {
            const pattern = /\[face_(\d+)\]/;
            for (let i = 0; i < data.msgs.length; i++) {
              messageList['msg_' + data.msgs[i].id] = data.msgs[i].id;
              if(pattern.test(data.msgs[i].msg)) {
                const faceId = data.msgs[i].msg.replace(/[^0-9]/ig,"");
                data.msgs[i].msg = '<img src="' + STATIC_BASE_URL + 'images/faces/'+faceId+'.gif' + '" height="80" width="80" class="face-img" />';
              }
            }

            that.msgList = data.msgs;
            // console.log(that.msgList);
            that.unlock = data.unlock;
            window.setTimeout(() => {
              that.$refs['msg_end'].scrollIntoView();
            }, 300);
            if(that.unlock) {
              that.EventBus.$emit('OnChatSessionConnect', null);
            }
          }
        }, response => {
          // error callback
        })
      },
      read(id) {
        const that = this;
        const url = chatMessageReadUri + '?id=' + id;
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.toast(msg);
          }
        }, response => {
          // error callback
        })
      },
      send(msg) {
        if(this.member.realname_auth_status == 0) {
          Dialog.confirm({
            message: '请先完成实名认证',
            theme: 'round-button',
          }).then(() => {
            // on close
            this.$router.push({name: 'MyAuthFaceId'});
          });
          return;
        }
        if(msg == null) {
          msg = document.getElementById('msgInput').value;
          if(msg.length == 0) {
            return;
          }
        }
        this.emojiWrapperVisible = false;
        const that = this;
        const formData = {
          to_uid: this.chatUser.id,
          msg: msg
        };
        that.$http.post(chatMessageSendUri, formData, {emulateJSON: true}).then(response => {
          let {msg, code, data} = response.body
          if (code != 0) {
            that.toast(msg);
          } else {
            that.msgContent = '';
            const pattern = /\[face_(\d+)\]/;
            if(pattern.test(data.chat.msg)) {
              const faceId = data.chat.msg.replace(/[^0-9]/ig,"");
              data.chat.msg = '<img src="' + STATIC_BASE_URL + 'images/faces/'+faceId+'.gif' + '" height="80" width="80" class="face-img" />';
            }
            that.msgList.push(data.chat);
            window.setTimeout(() => {
              this.$refs['msg_end'].scrollIntoView();
            }, 200);
          }
        }, response => {
          that.toast('发生错误')
        })
      },
      onMessageReceived(message) {
        const msg = JSON.parse(message);
        if(msg.send_uid == this.chatUser.id) {
          if(typeof messageList['msg_' + msg.id] != "undefined") {
            return;
          }
          messageList['msg_' + msg.id] = msg.id;

          const pattern = /\[face_(\d+)\]/;
          if(pattern.test(msg.msg)) {
            const faceId = msg.msg.replace(/[^0-9]/ig,"");
            msg.msg = '<img src="' + STATIC_BASE_URL + 'images/faces/'+faceId+'.gif' + '" height="80" width="80" class="face-img" />';
          }

          this.msgList.push(msg);
          this.read(msg.id);
          window.setTimeout(() => {
            this.$refs['msg_end'].scrollIntoView();
          }, 200);
        }
      }
    },
    created: function () {
      let _href = window.location.href;
      if (isWxServiceEnable && _href.indexOf('&replace=1') <= -1) {
        window.location.replace(_href + '&replace=1');
      }
    },
    mounted: function () {
      this.userId = this.$route.query.userId;

      this.member = this.GLOBAL.memberProfile;
      this.user = this.GLOBAL.userInfo;
      if(this.GLOBAL.siteConfig) {
        this.siteConfig = this.GLOBAL.siteConfig;
        this.chargePrice = this.siteConfig.prices.unlock_chat_session;
        if(this.GLOBAL.ws.connected == false) {
          this.EventBus.$emit('OnChatSessionConnect', null);
        }
      }

      this.EventBus.$on('OnUserLogined', () => {
        this.user = this.GLOBAL.userInfo;
        this.member = this.GLOBAL.memberProfile;
        this.getMemberProfile();
        if(this.GLOBAL.ws.connected == false) {
          this.EventBus.$emit('OnChatSessionConnect', null);
        }
      });

      this.EventBus.$on('OnSiteConfigLoaded', () => {
        this.siteConfig = this.GLOBAL.siteConfig;
        this.chargePrice = this.siteConfig.prices.unlock_chat_session;
      });

      this.EventBus.$on('OnMessageReceived', (message) => {
        this.onMessageReceived(message);
      });

      this.getJsApiConfig();
      if(this.user) {
        this.getMemberProfile();
      }
    }
  }
</script>

<style scoped>
  .send-input-wrapper {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    padding-bottom: env(safe-area-inset-bottom);
  }

  .send-input {
    background: #f2f2f2;
    padding: 6px;
    border-radius: 6px;
    border: none;
    width: 100%;
  }

  .emoji-wrapper {
    height: 150px;
    overflow-y: auto;
    overflow-x: hidden;
  }
  .emoji-wrapper .faces img {
    height: 30px;
    width: 30px;
  }

  .msg-wrapper {
    top: 40px;
    left: 0;
    right: 0;
    bottom: calc(60px + env(safe-area-inset-bottom));
    position: absolute;
    overflow-x: hidden;
    overflow-y: auto;
    opacity: 1;
  }

  .chat-member .avatar {
    height: 40px;
    width: 40px;
    border-radius: 20px;
  }

  .chat-member .info {
    width: 200px;
  }

  .chat-member .info .photo {
    width: 100%;
  }

  .receive-item .avatar, .send-item .avatar {
    height: 40px;
    width: 40px;
    border-radius: 20px;
  }

  .receive-item .content, .send-item .content {
    word-break: break-all;
    box-shadow: 0 1px 10px 0 rgba(0, 0, 0, 0.02);
    -webkit-box-shadow: 0 1px 10px 0 rgba(0, 0, 0, 0.02);
    vertical-align: top;
  }
  .receive-item .content {
    border-top-right-radius: 8px;
    border-bottom-right-radius: 8px;
    border-bottom-left-radius: 8px;
  }
  .send-item .content {
    background: #13ca87;
    border-top-left-radius: 8px;
    border-bottom-right-radius: 8px;
    border-bottom-left-radius: 8px;
  }
  .receive-item .content:after {
    content: "";
    position: absolute;
    top: 0;
    left: -0.16rem;
    width: 0;
    height: 0;
    border: 0.16rem solid transparent;
    border-top-color: transparent;
    border-top-color: #fff;
  }

  .send-item .content:after {
    content: "";
    position: absolute;
    top: 0;
    right: -0.16rem;
    width: 0;
    height: 0;
    border: 0.16rem solid transparent;
    border-top-color: #13ca87;
  }

  .receive-item .content .face-img, .send-item .content .face-img {
    height: 90px;
    width: 90px;
  }
</style>
